﻿using System;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using MS.InformationManagement.Presenter.DocumentPrinter;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Support;
using MS.InformationManagement.Support.Constants;
using Microsoft.SharePoint.Taxonomy;
using System.Collections.Generic;
using MS.InformationManagement.DAL.DTOs;
using MS.InformationManagement.DAL.DocumentCenter;

namespace MS.InformationManagement.WP.DocumentCenter.DocumentDeliveryConfig
{
    public partial class DocumentDeliveryConfigUserControl : BaseControl, IDocumentDeliveryConfigView
    {
        #region [Private Fields]

        private DocumentDeliveryConfigPresenter _Presenter;
        private Microsoft.SharePoint.Taxonomy.TaxonomyFieldValue _selectedTerm;
        private string _selectedCountry;
        private string _selectedState;

        #endregion

        #region [Event Handlers]

        protected void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                _Presenter.SendDeliveryMail();
            }
            catch (Exception ex) 
            { 
                HandleError(ex); 
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            string isDlg = Request.QueryString.Get("IsDlg");
            if (!string.IsNullOrEmpty(isDlg) && isDlg.Equals("1")) { this.CloseWindow(); }
            else { this.GoCurrentUserHome(); }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (IsPostBack) return;
                _Presenter.HandleLoad();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            _Presenter = new DocumentDeliveryConfigPresenter(this);            
            DocumentID = string.IsNullOrEmpty(Request.QueryString.Get("dID")) ? 0 : Convert.ToInt32(Request.QueryString.Get("dID"));
            LibraryName = Request.QueryString.Get("lName");
            txtbAddress.Required("Debe ingresar un valor para este campo", btnSend.ValidationGroup, AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            txtbPhoneNumber.Required("Debe ingresar un valor para este campo", btnSend.ValidationGroup, AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
        }

        protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                _Presenter.LoadStates();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                _Presenter.LoadCities();
            }
            catch (Exception ex)
            {
                HandleError(ex);
            }
        }

        #endregion

        #region [IDocumentDeliveryConfigView Members]

        public int DocumentID { get; set; }

        public IEnumerable<MedioDeEnvio> DeliveryMeans { get; set; }

        public string DocumentType { get; set; }

        public string ToFirstNameOrLegalReason
        {
            get
            {
                return txtbFirstNameOrLegalReason.Text;
            }
            set
            {
                txtbFirstNameOrLegalReason.Text = value;
            }
        }

        public string ToLastNameOrInitials
        {
            get
            {
                return txtbLastNameOrInitials.Text;
            }
            set
            {
                txtbLastNameOrInitials.Text = value;
            }
        }

        public string ToSecondLastNameOrCEO
        {
            get
            {
                return txtbSecondLastNameOrCEO.Text;
            }
            set
            {
                txtbSecondLastNameOrCEO.Text = value;
            }
        }

        public string ToPhoneNumber
        {
            get
            {
                return txtbPhoneNumber.Text;
            }
            set
            {
                txtbPhoneNumber.Text = value;
            }
        }

        public string ToEmail
        {
            get
            {
                return txtbEmail.Text;
            }
            set
            {
                txtbEmail.Text = value;
            }
        }

        public string LibraryName { get; set; }

        public string Address
        {
            get
            {
                return txtbAddress.Text;
            }
            set
            {
                txtbAddress.Text = value;
            }
        }

        public TermCollection Countries { get; set; }

        public TermCollection States { get; set; }

        public TermCollection Cities { get; set; }

        public TaxonomyFieldValue SelectedTerm
        {
            get
            {
                if (_selectedTerm != null)
                    return _selectedTerm;
                if (Cities == null) return null;
                Microsoft.SharePoint.Taxonomy.Term selTerm = (from city in Cities.OfType<Microsoft.SharePoint.Taxonomy.Term>()
                                                              where city.Name == ddlCity.SelectedValue
                                                              select city).FirstOrDefault();
                if (selTerm == null) return null;
                return TermStoreHelper.GetTaxomyFieldByTerm(selTerm);
            }
            set
            {
                _selectedTerm = value;
            }
        }


        public string SelectedCountry
        {
            get { return (string.IsNullOrEmpty(_selectedCountry)) ? ddlCountry.SelectedValue : _selectedCountry; }
            set { _selectedCountry = value; }
        }

        public string SelectedState
        {
            get { return string.IsNullOrEmpty(_selectedState) ? ddlState.SelectedValue : _selectedState; }
            set { _selectedState = value; }
        }

        public List<EnvíoDeCorrespondenciaDTO> Deliveries { get; set; }

        public void ChangeLabels()
        {
            txtbFirstNameOrLegalReason.Required("Debe ingresar un valor para este campo", btnSend.ValidationGroup, AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            switch (DocumentType)
            {
                case "RadicadoPersonaSalida":

                    lblFirstNameOrLegalReason.Text = "Nombres";
                    lblLastNameOrInitials.Text = "Apellido";
                    lblSecondLastNameOrCEO.Text = "Segundo Apellido";
                    //txtbLastNameOrInitials.Required("Debe ingresar un valor para este campo", btnSend.ValidationGroup, AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);

                    break;
                case "RadicadoEmpresaSalida":

                    lblFirstNameOrLegalReason.Text = "Razón Social";
                    lblLastNameOrInitials.Text = "Sigla";
                    lblSecondLastNameOrCEO.Text = "Representante Legal";
                    //txtbSecondLastNameOrCEO.Required("Debe ingresar un valor para este campo", btnSend.ValidationGroup, AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);

                    break;
            }
        }

        public void Show()
        {
            initDDlControls(ddlCountry, Countries, SelectedCountry, GlobalConstants.DDL_INITIAL_STATE_COUNTRY);
            initDDlControls(ddlCity, null, "0", GlobalConstants.DDL_INITIAL_STATE_CITY);
            initDDlControls(ddlState, null, GlobalConstants.DDL_INITIAL_STATE_STATE, GlobalConstants.DDL_INITIAL_STATE_STATE);
            if (!string.IsNullOrEmpty(SelectedState))
                initDDlControls(ddlState, States, SelectedState, GlobalConstants.DDL_INITIAL_STATE_STATE);
            if (SelectedTerm != null)
                initDDlControls(ddlCity, Cities, SelectedTerm.Label, GlobalConstants.DDL_INITIAL_STATE_CITY);
        }

        public void ShowStates()
        {
            initDDlControls(ddlState, States, SelectedState, GlobalConstants.DDL_INITIAL_STATE_STATE);
            initDDlControls(ddlCity, null, GlobalConstants.DDL_INITIAL_STATE_CITY, GlobalConstants.DDL_INITIAL_STATE_CITY);
        }

        public void ShowCities()
        {
            string selectedCities = SelectedTerm == null ? default(string) : SelectedTerm.Label[0].ToString();
            initDDlControls(ddlCity, Cities, selectedCities, GlobalConstants.DDL_INITIAL_STATE_CITY);
        }

        public void RaiseWarning(string message) {
            HandleWarning(message);
        }

        public void ShowMessage(string message)
        {
            this.ShowAlertAndClose(message);
        }


        #endregion

        #region [Private Members]

        private void initDDlControls(DropDownList ddlControl, Microsoft.SharePoint.Taxonomy.TermCollection datasource, string selectedValue, string initValue)
        {
            ddlControl.DataSource = datasource;
            ddlControl.DataBind();

            if (!string.IsNullOrEmpty(selectedValue))
                ddlControl.SelectedIndex = ddlControl.Items.IndexOf((from item in ddlControl.Items.OfType<ListItem>()
                                                                     where item.Text == selectedValue
                                                                     select item).FirstOrDefault());
            ddlControl.Items.Insert(0, new ListItem() { Value = "0", Text = initValue });
            ddlControl.CausesValidation = false;

        }

        #endregion

    }
}
